/**
 * Created by zhulizhe on 2017/8/8.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    Image,
    NativeModules,
    Platform
} from 'react-native';
import {observable, action, computed, observe} from 'mobx' ;
import LocationMgr from '../common/LocationManager' ;
import loginStore from '../store/LoginStore' ;
import RequestUtil from '../util/NetUtil'
import PermissionAndroidUtil from '../../luojs/util/PermissionAndroidUtil'

const AMapService = NativeModules.AMapService;
const LATITUDE_DELTA = 0.0005;
const LONGTITUDE_DELTA = 0.0005;


// activeAddress 地址模型
export class Address {
    @observable phone;
    @observable name;
    @observable mappingAddress;
    @observable appendAddress;
    @observable default;
    @observable addressTagName;

    // 创建新地址
    constructor(adCode = 0, appendAddress = '', cityCode = 0, cityName = '', latitude = 0.0, longtitude = 0.0, mappingAddress = '', name = '', pCode = 0, pName = 0, phone = '', selectTagId = '',addressTagName='') {
        this.adCode = adCode;
        this.appendAddress = appendAddress;
        this.cityCode = cityCode;
        this.cityName = cityName;
        this.latitude = latitude;
        this.longitude = longtitude;
        this.mappingAddress = mappingAddress;
        this.name = name;
        this.pCode = pCode;
        this.pName = pName;
        this.phone = phone;
        this.selectTagId = selectTagId;
        this.addressTagName = addressTagName;
    }
}

//用户地址列表
class DeliveryAddressListMgr {

    @observable _list = [];
    @observable _selectedAddress;//确认订单选中的收货地址
    @observable _isSelectAddress=false;//是否是从确认订单来选择地址
    constructor() {
        this.refreshList();
    }

    @computed
    get list() {
        return this._list;
    }

    // 获取默认收货地址
    @computed
    get defaultAddress() {
        let deFaultList = this._list.filter((addr) => addr.default == true);
        if (deFaultList.length > 0) {
            return deFaultList[0];
        }
        return null;
    }

    // 异步加载地址列表
    async refreshList() {
        //let hasLogin = await loginStore.loginState();
        //if (hasLogin) {
            const result = await RequestUtil.requestData('delivery/addressList', {})
            LOG('addressList##'+JSON.stringify(result));
            if (result && result.length >= 0) {
                this._list = result;
                this._selectedAddress=result[0];
            }
        //}
    }
    @action refreshDeliveryList(){
        this.refreshList();
    }
    @action setSelectedAddress(address){
        this._selectedAddress=address;
    }
    @computed get SelectedAddress(){
        return this._selectedAddress;
    }
    @action setIsSelectAddress(flag){
        this._isSelectAddress=flag;
    }
    @computed get isSelectAddress(){
        return this._isSelectAddress;
    }
}

//高德获取当前地址
class MapAuto {

    @observable _neighborList = [];
    @observable _addrListByKeyword = [];
    @observable _currentAddress = '';
    @observable _loading = true;
    @observable _cityName = '';
    @observable _tempPoi;//地图搜索某个搜索结果
    @observable _isEdit=false;//是否在编辑地址中修改区域

    // 用户选择地图显示位置[地图显示]
    @observable selectedRegion = {
        latitude: 0,
        longitude: 0,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGTITUDE_DELTA
    }

    constructor() {
        if(Platform.OS=='android')PermissionAndroidUtil.requestLocationPermission();

        this.startLocation();
        // 监听 showRegion的变化，重新获取附近地址列表
        observe(this, 'selectedRegion', (change) => {
            // 刷新附近的位置列表
            this.loadNeighborList();
        });

    }

    @action setEdit(edit){
        this._isEdit=edit;
    }
    @computed get edit(){
        return this._isEdit;
    }
    @action  setTempPoi(poi){
        this._tempPoi=poi;
        this.setEdit(true);
    }
    @computed get TempPoi(){
        return this._tempPoi;
    }
    // 设置地图上的当前位置
    @action
    setMapRegion(r) {
        this.selectedRegion = r;
    }

    // 获取附近列表
    @computed
    get neighborList() {
        return this._neighborList;
    }

    // 关键字搜索列表
    @computed
    get addrListByKeyword() {
        return this._addrListByKeyword;
    }

    // 当前位置
    @computed
    get currentAddress() {
        return this._currentAddress;
    }

    // 是否定位中
    @computed
    get loading() {
        return this._loading;
    }

    @computed
    get currentRegion() {
        let position = this.currentAddress;
        return {
            latitude: position.latitude,
            longitude: position.longitude,
            latitudeDelta: LATITUDE_DELTA,
            longitudeDelta: LONGTITUDE_DELTA
        }
    }

    convertPOI2Region(poi) {
        return {
            latitude: poi.location.latitude,
            longitude: poi.location.longitude,
            latitudeDelta: LATITUDE_DELTA,
            longitudeDelta: LONGTITUDE_DELTA
        }
    }

    // 当前城市
    @computed
    get city() {
        return this._cityName;
    }

    // 设置当前城市
    @action
    setCityName(name) {
        this._cityName = name;
    }

    // 开始定位
    startLocation() {
        LocationMgr.startLocation((poi) => {
            if (poi.errorInfo) return;
            // 设置当前位置
            let addr = this.convertPOI2Address(poi);
            this._currentAddress = addr;

            this._loading = false;

            // 设置当前城市
            this._cityName = poi.city ? poi.city : poi.province;

            // 搜索附近的地址列表
            AMapService.searchEvent(poi.latitude, poi.longitude, (result) => {
                this._neighborList = JSON.parse(result);
            });

            // 设置地图位置，默认为当前位置
            let r = {
                latitude: poi.latitude,
                longitude: poi.longitude,
                latitudeDelta: LATITUDE_DELTA,
                longitudeDelta: LONGTITUDE_DELTA
            }
            this.setMapRegion(r);
        });
    }


    // poi信息转化为地址模型
    convertPOI2Address(poi) {
        let province = poi.province;
        let city = poi.city;
        // 当前位置赋值
        let cityName = city != null ? poi.city : '北京';
        let pName = province != null ? province : '';

        // 生成 mappingAddress 逻辑
        let mappingAddress = '';

        {
            let province = poi.province;
            let city = poi.city;
            let district = poi.district;
            let address = poi.address;

            if (province && province.length) {
                mappingAddress += province;
            }
            else {
                if (city && city.length) {
                    mappingAddress += city;
                }
            }

            if (district && district.length) {
                mappingAddress += district;
            }
             if (address && address.length) {
                mappingAddress = address;
            }
            if(poi.name!=null){
                mappingAddress = poi.name
            }
            if(address!=null&&address.mapAddress!=null){
                mappingAddress = poi.address.mapAddress+poi.address.appendingAddress;
            }

            if(poi.aoiName!=null){
                mappingAddress = poi.aoiName
            }
        }
        //
        let pCode = 0;
        let la = 0;
        let lo = 0;
        let adCode = poi.adCode;
        let cityCode = poi.cityCode;

        if (poi.location != null) {
            la = poi.location.latitude;
            lo = poi.location.longitude
            adCode = poi.adcode;
            cityCode = poi.citycode;
            pCode = poi.pcode;
        }else if(poi.point!=null){
            la = parseFloat(poi.point.latitude);
            lo = parseFloat(poi.point.longitude);
            adCode=poi.adcode;
            pCode = poi.poiId;
        }else if(poi.position!=null){
            la = poi.position.latitude;
            lo = poi.position.longitude
        }
        else {
            la = poi.latitude;
            lo = poi.longitude;
            adCode = poi.adCode;
            cityCode = poi.cityCode;
        }
        return new Address(
            adCode,
            '',
            cityCode,
            cityName,
            la,
            lo,
            mappingAddress,
            '',
            pCode,
            pName,
            '',
            ''
        );
    }

    //关键字搜索地址列表
    @action
    searchByWord(keyword, city = this.city) {
        AMapService.searchAreaEvent(keyword, city, (result) => {
            if(Platform.OS=='android'){
                this._addrListByKeyword = JSON.parse(result) ;
            }else {
                if(result && (result instanceof Array)){
                this._addrListByKeyword = result ;
                }
            }
        })
    }

    // 请求附近地址列表
    @action
    loadNeighborList() {
        let la = this.selectedRegion.latitude;
        let lo = this.selectedRegion.longitude;
        AMapService.searchEvent(la, lo, (result) => {
            LOG('附近地址---------'+JSON.stringify(result));
                if(Platform.OS=='android'){
                    this._neighborList = JSON.parse(result) ;
                }
                else {
                    if (result && result instanceof Array) {

                        this._neighborList = result;
                }
            }
        })
    }

    @action
    refreshList() {
        this.startLocation();
    }
}

//统一管理地址的mng
class AddressMgr {

    @observable deliveryAddressListMgr;
    @observable mapAuto;
    @observable _activeAddress;
    //当前选择的城市
    @observable _selectedCity;

    constructor(deliveryAddressListMgr, mapAuto) {
        this.deliveryAddressListMgr = deliveryAddressListMgr;
        this.mapAuto = mapAuto;

        let addr = mapAuto.currentAddress;
        this._selectedCity = addr ? addr.city ? addr.city : addr.province : ''
    }

//如果没有默认地址，显示当前地址，如果有则显示默认地址
    @computed
    get activeAddress() {
        if (this._activeAddress != null) {
            return this._activeAddress;
        }
        let defaultAddress = this.deliveryAddressListMgr.defaultAddress;
        if (defaultAddress != null) {
            return defaultAddress;
        }
        return this.mapAuto.currentAddress;
    }

    @action
    setSelected(address) {
        LOG('setSelected-------'+JSON.stringify(address));
        this._activeAddress = address;
    }

    @computed
    get neighborList() {
        return this.mapAuto.neighborList;
    }

    @computed
    get deliveryList() {
        return this.deliveryAddressListMgr.list;
    }

    @computed
    get activeCity() {
        return this.mapAuto.city;
    }

    // 设置当前选择的城市 [用于搜索]
    @action
    setCity(name) {
        this.mapAuto.setCityName(name);
        this.searchCityChange();
    }

    @action
    searchCityChange(){
        AMapService.searchAreaEvent('政府', this.activeCity, (result) => {
            LOG('切换城市---------'+JSON.stringify(result));
            if(Platform.OS=='android'){
                this.mapAuto._addrListByKeyword = JSON.parse(result) ;
                let addrM = addressMgrStore.mapAuto.convertPOI2Address(this.mapAuto._addrListByKeyword[0]);
                addressMgrStore.setSelected(addrM);
                this.mapAuto.setMapRegion(addrM);
            }else {
                if(result && (result instanceof Array)){
                    this.mapAuto._addrListByKeyword = result ;
                }
            }
        });

    }
    // 重新定位
    @action
    refreshMyLocation() {
        this.mapAuto.refreshList();
    }

    @action refreshDeliveryList(){
        this.deliveryAddressListMgr.refreshDeliveryList();
    }
}

let mapAuto = new MapAuto();
let addressListMgr = new DeliveryAddressListMgr();
let addressMgrStore = new AddressMgr(addressListMgr, mapAuto);

export default addressMgrStore


